package com.darrenchan.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-04-19 21:41
 */
public class QLint57 {
    public List<List<Integer>> threeSum(int[] numbers) {
        if(numbers == null || numbers.length < 3) {
            return null;
        }

        Arrays.sort(numbers);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < numbers.length - 2; i++) {
            while(i > 0 && i < numbers.length - 2 && numbers[i] == numbers[i - 1]) {
                i++;
            }
            findTwoNum(numbers, i + 1, numbers.length - 1, -numbers[i], res);
        }
        return res;
    }

    private void findTwoNum(int[] numbers, int i, int j, int target, List<List<Integer>> res) {
        while(i < j) {
            if(numbers[i] + numbers[j] == target) {
                List<Integer> subarray = new ArrayList<>();
                subarray.add(-target);
                subarray.add(numbers[i]);
                subarray.add(numbers[j]);
                res.add(subarray);

                i++;
                j--;
                while(i < j && numbers[i] == numbers[i - 1]) {
                    i++;
                }
                while(i < j && numbers[j] == numbers[j + 1]) {
                    j--;
                }
            } else if(numbers[i] + numbers[j] < target) {
                i++;
            } else {
                j--;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new QLint57().threeSum(new int[]{1,0,-1,-1,-1,-1,0,1,1,1}));
    }
}
